package com.huanlis.consumer.thread;

import com.huanlis.consumer.util.LocalState;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.locks.LockSupport;

@Slf4j
public class AsyncThread extends Thread {

    private LocalCache localCache;

    private Object lock;

    public AsyncThread(Object object, LocalCache localCache) {
        this.lock = object;
        this.localCache = localCache;
    }

    @Override
    public void run() {
        LocalState cache = localCache.getCache();
        log.info("异步线程启动：{}----{}", Thread.currentThread().getName(), cache.getId());
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(cache.getUrl() + cache.getId(), String.class);
        if (response.getStatusCode().isError()) {
            log.error("异步请求错误：{}----{}", Thread.currentThread().getName(), cache.getId());
            cache.setSuccess(false);
        } else {
            cache.setSuccess(true);
            cache.setResult(response.getBody());
        }
        localCache.setCache(cache);
        LockSupport.unpark((Thread)lock);
        log.info("异步线程结束：{}----{}", Thread.currentThread().getName(), cache.getId());
    }
}
